﻿Option Explicit On

Imports System.Xml
Imports System.IO
Imports System.Net
Imports System.Data
Imports System.Linq
Imports System.Text
Imports MAPI
Imports Global_Visas_Business_Layer
Imports Outlook = Microsoft.Office.Interop.Outlook
'Imports Aspose.Network.Exchange


Imports System.Security.Authentication

Imports System.Web

Partial Public Class frmMailbox
    Private myMAPI As New MAPI.Session
    Private myFolder As MAPI.Folder
    Private myMessages As MAPI.Messages


    Private Enum Direction
        Forward = 1
        Backward = 2
    End Enum
    Private _MailIndex As Long
    Private Property MailIndex() As Long
        Get
            Return _MailIndex
        End Get
        Set(ByVal value As Long)
            _MailIndex = value
        End Set
    End Property
    Private _MailFromIndex As Integer
    Private Property MailFromIndex() As Integer
        Get
            Return _MailFromIndex
        End Get
        Set(ByVal value As Integer)
            _MailFromIndex = value
        End Set
    End Property
    Private _MailToIndex As Integer
    Private Property MailToIndex() As Integer
        Get
            Return _MailToIndex
        End Get
        Set(ByVal value As Integer)
            _MailToIndex = value
        End Set
    End Property
    Private _MailFolder As String
    Private Property MailIFolder() As String
        Get
            Return _MailFolder
        End Get
        Set(ByVal value As String)
            _MailFolder = value
        End Set
    End Property

    Private Sub frmMailbox_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Me.KeyUp

    End Sub

    Private Sub frmMailbox_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        'Me.MailIndex = 0
        Dim progressBar As frmProgressBar = Nothing
        Dim strprofile As String
        Try

            progressBar = New frmProgressBar()
            progressBar.TextToDisplay = "Dear " & GlobalCRM.CurrentConName & ", please wait while CRM loads the emails for you....."
            progressBar.Show()
            GeneralTasks.ChangeTheme(Me)
            GeneralTasks.EnumerateandFill(Me.LogicalChildren)
            btnPrev.IsEnabled = False
            'myMAPI.Logon("", "", True, True, 0, True, "Orion" & vbLf & GlobalCRM.CurrentNTUserName)
            'myMAPI.Logon("", "", True, True, 0, True, "Orion" & vbLf & GlobalCRM.CurrentNTUserName)
            'myMAPI.Logon("gv\" & GlobalCRM.CurrentNTUserName, GlobalCRM.CurrentNTPassword, True, True, 0, True, "pop3.globalvisas.com" & vbLf & GlobalCRM.CurrentNTUserName)


            Try
                If Environment.UserDomainName.ToUpper = "GV" Then
                    myMAPI.Logon("", "", True, True, 0, True, "Orion" & vbLf & GlobalCRM.CurrentNTUserName)
                    'strprofile = "10.0.0.32" & vbLf & GlobalCRM.CurrentNTUserName
                Else
                    'strprofile = "217.33.159.220" & vbLf & GlobalCRM.CurrentNTUserName
                End If
                

                'myMAPI.Logon("gv\" & GlobalCRM.CurrentNTUserName, GlobalCRM.CurrentNTPassword, True, True, 0, True, strprofile)

            Catch ex1 As Exception
                CommonFuncs.DisplayMessage("Login to exchange server failed. please make sure that you have updated your NT password on CRM." & vbCrLf & "Contact IT for more information", CommonDialog.CustomDialogIcons.Stop, "Exchange server")
                Exit Sub
            End Try
            'myMAPI.Logon(,,,,,,




            myFolder = myMAPI.Inbox
            MailIFolder = "inbox"

            'Me.GetInboxMAPI_Display(myFolder, myFolder.Messages.count, myFolder.Messages.count - 49, True)
            MailFolders.FireEvent("inbox")
            'Dim str As New StringBuilder()
            'For index As Integer = 0 To 8
            '    myFolder = myMAPI.GetDefaultFolder(index)
            '    If index = 4 Then
            '        DeletedFolderId = myFolder.FolderID
            '        DeletedFolderStoreId = myFolder.StoreID
            '    End If
            '    str.AppendLine("Index :" + index.ToString() + "-----" + myFolder.Name)
            'Next
            'MsgBox(str.ToString())

            myFolder = myMAPI.GetDefaultFolder(3)
            RefreshEmailCounters()
            progressBar.Close()
        Catch ex As Exception
            CommonFuncs.DisplayMessage(ex.Message, CommonDialog.CustomDialogIcons.Stop, "Mailbox")
        Finally
            progressBar.Close()
        End Try
    End Sub

    Private Sub MailFolders_Bang(ByVal textBlockName As System.String) Handles MailFolders.Bang
        Try


            If textBlockName.ToUpper() = "INBOX" Then
                MailIFolder = "inbox"
                LoadItems(1)
            ElseIf textBlockName.ToUpper() = "SENTITEMS" Then
                MailIFolder = "sentitems"
                LoadItems(3)
            ElseIf textBlockName.ToUpper() = "DELETED" Then
                MailIFolder = "deleted"
                LoadItems(4)
            End If
            'txtFrom.Text = 1
            'MailFromIndex = 1
            txtMessage.Text = String.Empty
        Catch ex As Exception

        End Try
    End Sub

    Public Sub GetInboxMAPI_Display(ByVal myfolder As MAPI.Folder, ByVal StartPos As Integer, ByVal EndPos As Integer, ByVal blnNext As Boolean)

        'Sumathivinayak S - Logic completely re-written as the previous was retriving the emails in the reverse order. That is,
        'the older logic was displaying the recent email at the last and hence the user has to move to the last to select the recent one.
        'Krishan K Kaliraman - Logic further extended to show the refreshed emails with the counters of the emails as well

        MailFromIndex = StartPos
        MailToIndex = EndPos
        Try


            Dim myInbox As New DataTable
            Dim myRow As DataRow
            Dim intCtr As Integer
            'Me.Cursor = Cursors.WaitCursor
            With myInbox.Columns
                .Add(New DataColumn("Subject", System.Type.GetType("System.String")))
                .Add(New DataColumn("Sender", System.Type.GetType("System.String")))
                .Add(New DataColumn("Received", System.Type.GetType("System.DateTime")))
                .Add(New DataColumn("Attachments", System.Type.GetType("System.Int16")))
                .Add(New DataColumn("ID", System.Type.GetType("System.String")))
            End With

            ' Me.lblMsgCount.Text = myfolder.Messages.count
            myMessages = myfolder.Messages

            For intCtr = StartPos To EndPos Step -1
                If intCtr = 0 Then
                    intCtr = intCtr + 1
                    Exit For
                End If
                myRow = myInbox.NewRow
                myRow.Item("Subject") = myMessages.Item(intCtr).Subject
                ' myRow.Item("Sender") = CType(myMessages.Item(intCtr).Sender, MAPI.AddressEntry).Name
                myRow.Item("Sender") = R_GetSenderAddress(myMessages.Item(intCtr))
                myRow.Item("Received") = myMessages.Item(intCtr).TimeReceived
                myRow.Item("Attachments") = CType(myMessages.Item(intCtr).Attachments, MAPI.Attachments).Count
                myRow.Item("ID") = CType(myMessages.Item(intCtr), MAPI.Message).ID
                myInbox.Rows.Add(myRow)

            Next


            'If blnNext Then
            '    Me.MailIndex = intCtr
            'Else
            '    Me.MailIndex = intCtr + 51
            'End If
            Me.MailIndex = intCtr

            '''''''''''''''''''''''''''''''''''''
            'new


            'Dim bind As New Binding()
            'bind.Source = myInbox
            'grdInbox.SetBinding(ListView.ItemsSourceProperty, bind)

            DataBinding.BindListView(myInbox, grdInbox)

            '''''''''''''''''''''''''''''''''''''

            'Me.grdInbox.DataSource = myInbox

            'Me.grdInbox.Columns(0).Width = "400"
            'Me.grdInbox.Columns(1).Width = "150"
            'Me.grdInbox.Columns(2).Width = "100"
            'Me.grdInbox.Columns(3).Width = "75"
            'Me.grdInbox.Columns(4).Visible = False
            'Me.Cursor = Cursors.Default
        Catch ex As Exception
            CommonFuncs.DisplayMessage("Error Opening the Inbox. Please contact IT for assistance - " & ex.Message.ToString, CommonDialog.CustomDialogIcons.Information, "Error!")
            'Me.Enabled = False
        Finally
            RefreshEmailCounters()
        End Try
    End Sub

    Private Function R_GetSenderAddress(ByVal objMsg) As Object
        Dim objSenderAE ' Redemption.AddressEntry
        Dim objSMail    ' Redemption.SafeMailItem
        Try


            Dim strType

            Const PR_SENDER_ADDRTYPE = &HC1E001E
            Const PR_EMAIL = &H39FE001E
            Dim returnValue As Object = Nothing
            objSMail = CreateObject("Redemption.SafeMailItem")
            objSMail.Item = objMsg
            strType = objSMail.Fields(PR_SENDER_ADDRTYPE)
            objSenderAE = objSMail.Sender
            If Not objSenderAE Is Nothing Then
                If strType = "SMTP" Then
                    returnValue = objSenderAE.Address
                ElseIf strType = "EX" Then
                    returnValue = objSenderAE.Fields(PR_EMAIL)
                End If
            End If
            Return returnValue


        Catch ex As Exception
            Return Nothing
        Finally
            objSenderAE = Nothing
            objSMail = Nothing
        End Try
    End Function


    Private Function GetMessageMAPI(ByVal MessageId As String) As String
        ' get message body for selected email

        Dim myMAPI As New MAPI.Session
        Dim myFolder As MAPI.Folder = Nothing
        Dim myMessage As MAPI.Message
        'Dim myMessages As MAPI.Messages

        Try

            myMAPI.Logon("", "", True, True, 0, True, "Orion" & vbLf & GlobalCRM.CurrentNTUserName)

            'myMAPI.Logon("", "", True, True, 0, True, "Reliant" & vbLf & "marting")
            'myMAPI.Logon("", "", True, True, 0, True, "Orion" & vbLf & Environment.UserName) 

            If MailIFolder = "inbox" Then
                myFolder = myMAPI.Inbox
            ElseIf MailIFolder = "sentitems" Then
                myFolder = myMAPI.GetDefaultFolder(3)
            ElseIf MailIFolder = "deleted" Then
                myFolder = myMAPI.GetDefaultFolder(4)
            End If

            'myMessages = myFolder.Messages

            GetMessageMAPI = String.Empty    ' set default value


            ' loop through all messages to find the selected one (not very efficient, but it works)
            For Each myMessage In myFolder.Messages
                If myMessage.ID = MessageId Then

                    GetMessageMAPI = GetMessageMAPI & vbCrLf & "Received on " & myMessage.TimeCreated.ToString & vbCrLf & vbCrLf & "Subject: " & myMessage.Subject.ToString & vbCrLf & vbCrLf & "Body :" & vbCrLf & myMessage.Text.ToString
                End If
            Next

            'myMessage = myMessages.Item(MessageId)
            'GetMessageMAPI = myMessage.Text.ToString
            'myMessage = myMAPI.GetMessage(MessageId) ', StoreId)
            'GetMessageMAPI = myMessage.Text



        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMailbox.GetMessageMAPI")
            Return String.Empty
        Finally
            myMAPI.Logoff()

        End Try

    End Function

    Private Function DeleteMessageMAPI(ByVal MessageId As String) As String

        Dim myMAPI As New MAPI.Session
        Dim myDestinationFolder As MAPI.Folder
        Dim myfolder As MAPI.Folder
        Dim myMessage As MAPI.Message
        'Dim messages As MAPI.Messages
        'MsgBox(MailIFolder.ToString())
        Dim returnValue As String = String.Empty
        Try
            myMAPI.Logon("", "", True, True, 0, True, "Orion" & vbLf & GlobalCRM.CurrentNTUserName)
            If MailIFolder = "inbox" Then
                myfolder = myMAPI.GetDefaultFolder(1)
                For Each myMessage In myfolder.Messages
                    If myMessage.ID = MessageId Then
                        myDestinationFolder = myMAPI.GetDefaultFolder(4)
                        'myMessage.Delete()
                        myMessage.MoveTo(myDestinationFolder.FolderID, myDestinationFolder.StoreID)
                        returnValue = "inbox"
                    End If
                Next
            ElseIf MailIFolder = "sentitems" Then
                myfolder = myMAPI.GetDefaultFolder(3)
                For Each myMessage In myfolder.Messages
                    If myMessage.ID = MessageId Then
                        'With myme
                        myDestinationFolder = myMAPI.GetDefaultFolder(4)
                        myMessage.MoveTo(myDestinationFolder.FolderID)
                        returnValue = "sentitems"
                    End If
                Next
            ElseIf MailIFolder = "deleted" Then
                myfolder = myMAPI.GetDefaultFolder(4)
                For Each myMessage In myfolder.Messages
                    If myMessage.ID = MessageId Then
                        myMessage.Delete()
                        returnValue = "deleted"
                    End If
                Next
            End If
            Return returnValue

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Return String.Empty
        Finally
            myMessage = Nothing
            myMAPI.Logoff()
            RefreshEmailCounters()

        End Try

    End Function

    Private Sub LoadItems(ByVal intBox As Integer)
        Try


            'btnPrev.Enabled = False
            myFolder = myMAPI.GetDefaultFolder(intBox)
            If myFolder.Messages.count > 0 Then
                txtFrom.Text = 1
                btnFirst.IsEnabled = False
                btnPrev.IsEnabled = False
                If myFolder.Messages.count >= 50 Then
                    txtTo.Text = 50
                Else
                    txtTo.Text = myFolder.Messages.count
                End If
            End If

            Me.GetInboxMAPI_Display(myFolder, myFolder.Messages.count, myFolder.Messages.count - 49, True)
            'Me.Cursor = Cursors.Default
        Catch ex As Exception

        End Try
    End Sub

    Private Sub DeleteMail_LostFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles DeleteMail.LostFocus
        Dim result As MsgBoxResult
        result = MsgBox("Delete the email ?", MsgBoxStyle.OkCancel)
        Try

            If result = MsgBoxResult.Ok Then
                'MsgBox("Ok Clicked!")    

                Dim currentRowIndex As Integer = grdInbox.SelectedIndex
                Dim currentRow As DataRowView = CType(grdInbox.Items(currentRowIndex), DataRowView)
                If Not currentRow Is Nothing Then
                    DeleteMessageMAPI(currentRow(4))

                End If
            ElseIf result = MsgBoxResult.Cancel Then
                'MsgBox("Cancel Clicked!")

            End If

        Finally
            If MailIFolder = "inbox" Then
                LoadItems(1)
            ElseIf MailIFolder = "sentitems" Then
                LoadItems(3)
            ElseIf MailIFolder = "deleted" Then
                LoadItems(4)
            End If
            txtMessage.Text = String.Empty
            RefreshEmailCounters()
        End Try


    End Sub

    Private Sub RefreshEmailCounters()

        Try
            myFolder = myMAPI.Inbox
            MailFolders.TotalInboxItems = "(" + myFolder.Messages.count.ToString() + ")"
            myFolder = myMAPI.GetDefaultFolder(3)
            MailFolders.TotalSentItems = "(" + myFolder.Messages.count.ToString() + ")"
            myFolder = myMAPI.GetDefaultFolder(4)
            MailFolders.TotalDeletedItems = "(" + myFolder.Messages.count.ToString() + ")"

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub btnPrev_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnPrev.Click
        Try


            If MailIFolder = "inbox" Then
                myFolder = myMAPI.GetDefaultFolder(1)
            ElseIf MailIFolder = "sentitems" Then
                myFolder = myMAPI.GetDefaultFolder(3)
            ElseIf MailIFolder = "deleted" Then
                myFolder = myMAPI.GetDefaultFolder(4)
            End If
            If Me.MailIndex = 1 Then
                GetInboxMAPI_Display(myFolder, 50 - (CInt(txtTo.Text) - myMessages.Count) + 50, 50 - (CInt(txtTo.Text) - myMessages.Count) + 1, False)
            Else
                If btnNext.IsEnabled = True And btnPrev.IsEnabled = True Then
                    GetInboxMAPI_Display(myFolder, Me.MailIndex + 100, Me.MailIndex + 51, False)
                Else
                    GetInboxMAPI_Display(myFolder, Me.MailIndex + 49, Me.MailIndex, False)
                End If
            End If
            If Me.MailIndex - 1 = myMessages.Count Then
                Me.MailIndex = Me.MailIndex - 1 - 49
                btnPrev.IsEnabled = False
            End If
            Me.txtFrom.Text = Me.txtFrom.Text - 50
            Me.txtTo.Text = Me.txtTo.Text - 50
            If myFolder.Messages.count > CInt(Me.txtTo.Text) Then
                btnNext.IsEnabled = True
            Else
                btnNext.IsEnabled = False
            End If
            If CInt(Me.txtFrom.Text) = 1 Then
                btnPrev.IsEnabled = False
                btnNext.IsEnabled = True
            Else
                btnPrev.IsEnabled = True
            End If
        Catch ex As Exception

        End Try
    End Sub




    Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnNext.Click
        Try
            If MailIFolder = "inbox" Then
                myFolder = myMAPI.GetDefaultFolder(1)
            ElseIf MailIFolder = "sentitems" Then
                myFolder = myMAPI.GetDefaultFolder(3)
            ElseIf MailIFolder = "deleted" Then
                myFolder = myMAPI.GetDefaultFolder(4)
            End If
            txtTo.Text = CInt(txtTo.Text) + 50
            txtFrom.Text = CInt(txtFrom.Text) + 50
            GetInboxMAPI_Display(myFolder, Me.MailIndex, Me.MailIndex - 49, True)

            If Me.MailIndex = 1 Then
                btnNext.IsEnabled = False
            End If
            If myFolder.Messages.count > CInt(Me.txtTo.Text) Then
                btnPrev.IsEnabled = True
                btnFirst.IsEnabled = True
            Else
                btnPrev.IsEnabled = True
                btnFirst.IsEnabled = True
            End If
        Catch ex As Exception

        End Try
    End Sub


    Private Sub btnLast_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnLast.Click
        Try
            If MailIFolder = "inbox" Then
                myFolder = myMAPI.GetDefaultFolder(1)
            ElseIf MailIFolder = "sentitems" Then
                myFolder = myMAPI.GetDefaultFolder(3)
            ElseIf MailIFolder = "deleted" Then
                myFolder = myMAPI.GetDefaultFolder(4)
            End If
            If myFolder.Messages.count > 0 Then

                If myFolder.Messages.count < 50 Then
                    txtFrom.Text = 1
                    txtTo.Text = myFolder.Messages.count
                Else
                    txtFrom.Text = myFolder.Messages.count - 50
                    txtTo.Text = myFolder.Messages.count
                    Me.GetInboxMAPI_Display(myFolder, 50, 0, True)
                    btnFirst.IsEnabled = True
                    btnPrev.IsEnabled = True
                End If
            Else
                txtFrom.Text = 0
                txtTo.Text = 0

            End If
            btnNext.IsEnabled = False
        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnFirst.Click
        Try
            If MailIFolder = "inbox" Then
                LoadItems(1)
            ElseIf MailIFolder = "sentitems" Then
                LoadItems(3)
            ElseIf MailIFolder = "deleted" Then
                LoadItems(4)
            End If
            btnNext.IsEnabled = True
            btnLast.IsEnabled = True
            btnNext.IsEnabled = True
            txtMessage.Text = String.Empty
        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub btnAddEvent_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddEvent.Click
        Dim cmn As New Global_Visas_Business_Layer.WriteLog
        Dim tsk As New Global_Visas_Business_Layer.TasksEvents

        Try


            ' add the selected message as an event for the current case
            'Dim strDate As String

            If grdInbox.SelectedItems.Count = 0 Then
                CommonFuncs.DisplayMessage("Please select an email.", CommonDialog.CustomDialogIcons.Information, "Info")
                Exit Sub
            End If
            Dim strRecorSend As String = String.Empty
            Dim blnDocsAdded As Boolean
            Dim strMessage As String
            ' load attachments to docstore
            If MailIFolder.ToUpper = "INBOX" Then
                strRecorSend = "Email Received"
            ElseIf MailIFolder.ToUpper = "SENTITEMS" Then
                strRecorSend = "Email Sent"
            End If
            Dim currentRowIndex As Integer = grdInbox.SelectedIndex
            Dim currentRow As DataRowView = CType(grdInbox.Items(currentRowIndex), DataRowView)
            Select Case Me.chkLoadAttachments.IsChecked
                Case True
                    If Me.txtMessage.Text.Trim.ToString <> "" Then
                        'If CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(3).Value() > 0 Then
                        '    If MsgBox("This email has no message." & vbCrLf & "Would you like to continue adding attachments to the document store?", MsgBoxStyle.YesNo, "No Message") = MsgBoxResult.No Then
                        '        Exit Sub
                        '    End If
                        'End If

                        'cmn.WriteToErrorLog("Me.txtMessage.Text.Trim.ToString", "Passed", "Mailbox", WriteLog.ErrorType.ErrorOnly)

                        If Not currentRow Is Nothing Then
                            If Not currentRow(4) Is Nothing Then
                                Dim Msg As New StringBuilder
                                If GetMessageMAPIAttachments(currentRow(4)) = True Then
                                Else
                                    Exit Sub
                                End If
                            End If
                        End If

                        blnDocsAdded = True
                        'Me.Dispose()
                        If Me.txtEventNote.Text.ToString <> "" Then
                            strMessage = Me.txtEventNote.Text.ToString & vbCrLf & vbCrLf & "---------------------------------------------------------------" & vbCrLf & vbCrLf & Me.txtMessage.Text.ToString
                        Else
                            strMessage = Me.txtMessage.Text.ToString
                        End If
                        'strDate = GetEmailArrivalDate(CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(4).Value())
                        tsk.GblFunc_Add_Event(strRecorSend, strMessage, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, , , , , , DateTime.Today)
                        CommonFuncs.DisplayMessage("The email has been added as event and the documents are stored in Document Store.", CommonDialog.CustomDialogIcons.Information, "Success")
                    ElseIf Me.txtMessage.Text.Trim.ToString = String.Empty Then
                        If currentRow(3) > 0 Then
                            If MsgBox("This email has no message." & vbCrLf & "Would you like to continue adding attachments to the document store?", MsgBoxStyle.YesNo, "No Message") = MsgBoxResult.No Then
                                Exit Sub
                            Else
                                If GetMessageMAPIAttachments(currentRow(4)) = True Then
                                    blnDocsAdded = True
                                    If Me.txtEventNote.Text.ToString <> "" Then
                                        strMessage = Me.txtEventNote.Text.ToString & vbCrLf & vbCrLf & "---------------------------------------------------------------" & vbCrLf & vbCrLf & Me.txtMessage.Text.ToString
                                    Else
                                        strMessage = Me.txtMessage.Text.ToString
                                    End If
                                    'strDate = GetEmailArrivalDate(CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(4).Value())
                                    tsk.GblFunc_Add_Event(strRecorSend, strMessage, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, , , , , , DateTime.Today)
                                    CommonFuncs.DisplayMessage("The email has been added as event and the documents are stored in Document Store.", CommonDialog.CustomDialogIcons.Information, "Success")
                                    Exit Sub
                                End If
                            End If
                        Else
                            CommonFuncs.DisplayMessage("This email has no message.", CommonDialog.CustomDialogIcons.Information, "No message")
                        End If

                        Exit Sub
                    End If
                Case False
                    If Me.txtEventNote.Text.ToString = String.Empty Then
                        'If blnDocsAdded Then
                        If Me.txtMessage.Text.Trim.ToString = String.Empty Then
                            CommonFuncs.DisplayMessage("This email has no message.", CommonDialog.CustomDialogIcons.Information, "No message")
                            Exit Sub

                        End If
                        'End If
                        strMessage = Me.txtEventNote.Text.ToString & vbCrLf & vbCrLf & "---------------------------------------------------------------" & vbCrLf & vbCrLf & Me.txtMessage.Text.ToString
                    Else
                        strMessage = Me.txtMessage.Text.ToString
                    End If
                    'strDate = GetEmailArrivalDate(CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(4).Value())
                    If tsk.GblFunc_Add_Event(strRecorSend, strMessage, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, , , , , , DateTime.Today) > 0 Then
                        CommonFuncs.DisplayMessage("The email has been added as event.", CommonDialog.CustomDialogIcons.Information, "Success")
                    End If
            End Select

            If Me.chkKeepOpen.IsChecked = False Then
                Me.Close()
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMailbox : btnAddEvent_Click")
        Finally
            cmn = Nothing
            tsk = Nothing
        End Try
    End Sub

    Private Sub btnReply_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnReply.Click
        ' reply to the selected email
        Dim frmSendEmail As New frmSendEmail
        Dim sbBody As New StringBuilder
        Try
            If grdInbox.SelectedItems.Count = 0 Then
                CommonFuncs.DisplayMessage("Please select an email.", CommonDialog.CustomDialogIcons.Information, "Info")
                Exit Sub
            End If
            If GlobalCRM.CurrentCompanyID > 0 Then
                If GlobalCRM.CurrentContactID > 0 Then
                    If (MsgBox("Would you like to reply to the contact? ; selecting NO would send a reply to candidate.", MsgBoxStyle.YesNo, "Email To") = MsgBoxResult.Yes) Then
                        frmSendEmail.iEmailType = CommonDataFunctions.EmailType.Contact
                    Else
                        frmSendEmail.iEmailType = CommonDataFunctions.EmailType.Candidate
                    End If
                Else
                    frmSendEmail.iEmailType = CommonDataFunctions.EmailType.Candidate
                End If
            Else
                frmSendEmail.iEmailType = CommonDataFunctions.EmailType.Candidate
            End If

            Dim currentRowIndex As Integer = grdInbox.SelectedIndex
            Dim myRow As DataRowView = CType(grdInbox.Items(currentRowIndex), DataRowView)

            'frmSendEmail.MdiParent = frmMDIMain
            'frmSendEmail.Show()
            'If Not People.GetCandidateEmailAddress(GlobalCRM.CurrentCaseID) Is Nothing Then
            '        frmSendEmail.txtTo.Text = People.GetCandidateEmailAddress(GlobalCRM.CurrentCaseID).ToString
            'End If
            'frmSendEmail.txtTo.Text = myRow.Cells(1).Value.ToString      ' this is bringing up the display name, ie "John Smith" instead of the underlying email address
            'frmSendEmail.txtSubject.Text = myRow(0).ToString

            If chkQuoteMessage.IsChecked = True Then
                With sbBody
                    .Append(vbCrLf & vbCrLf & vbCrLf)
                    .Append("-----------------------------------------------------------------------------------------------------------" & vbCrLf)
                    .Append(vbCrLf)
                    .Append("From: " & myRow(1).ToString() & vbCrLf)
                    .Append("Sent: " & myRow(2).ToString() & vbCrLf)
                    .Append("To: " & GlobalCRM.CurrentConName & vbCrLf)
                    .Append("Subject: " & myRow(0).ToString() & vbCrLf & vbCrLf)
                    .Append(Me.txtMessage.Text.ToString)
                End With

                Dim range As TextRange

                range = New TextRange(frmSendEmail.txtbody.Document.ContentStart, frmSendEmail.txtbody.Document.ContentEnd)
                range.Text = vbCrLf & vbCrLf & vbCrLf & vbCrLf & "----------------------Reply Separator--------------------------" & vbCrLf & vbCrLf & sbBody.ToString
                'frmSendEmail.txtSubject.Text = .Description


                'Dim stream As MemoryStream = New MemoryStream(ASCIIEncoding.Default.GetBytes(sbBody.ToString))
                'frmSendEmail.txtbody.Selection.Load(stream, DataFormats.Rtf)

                frmSendEmail.txtTo.Text = myRow(1).ToString()
                frmSendEmail.txtSubject.Text = "Re: " & myRow(0).ToString()
            End If

            If Me.chkKeepOpen.IsChecked = False Then
                frmSendEmail.Show()
                Me.Close()
            End If

        Catch ex As Exception
        Finally
            sbBody = Nothing
            frmSendEmail = Nothing
        End Try
    End Sub

    Private Function GetMessageMAPIAttachments(ByVal MessageId As String) As Boolean
        Dim cmn As New Global_Visas_Business_Layer.CommonFuncs
        Try

            Dim oApp As Outlook.Application = New Outlook.Application
            Dim storeid As String
            Dim oNS As Outlook.NameSpace = oApp.GetNamespace("MAPI")
            Dim oInbox As Outlook.MAPIFolder = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
            Dim oItems As Outlook.Items = oInbox.Items
            Dim oMsg As Outlook.MailItem
            Dim objAttach As Outlook.Attachment
            Dim colattach As Outlook.Attachments
            Dim DocStoreId As Long
            storeid = oInbox.StoreID
            oMsg = oNS.GetItemFromID(MessageId, storeid)
            colattach = oMsg.Attachments
            'Dim fso As New FileSystemObject
            cmn.ForceDeleteTempDir()
            'If Directory.Exists(System.IO.Path.GetTempPath & "CRMTemp") Then

            '    Dim i As Integer
            '    Dim FileNames() As String = Directory.GetFiles(System.IO.Path.GetTempPath & "CRMTemp")
            '    For i = 0 To FileNames.Length - 1
            '        'System.IO.File.Delete(FileNames(i))
            '        Dim fso As New Scripting.FileSystemObject
            '        fso.DeleteFile(FileNames(i), True)
            '    Next
            '    Directory.Delete(System.IO.Path.GetTempPath & "CRMTemp")
            'End If
            Directory.CreateDirectory(System.IO.Path.GetTempPath & "CRMTemp")
            For Each objAttach In colattach
                If Not objAttach Is Nothing Then
                    DocStoreId = Letters.GblFunc_Create_DocStore(objAttach.FileName, "Loaded as Email Event", GlobalCRM.CurrentCaseID)
                    objAttach.SaveAsFile(System.IO.Path.GetTempPath & "CRMTemp" & "\" & objAttach.FileName)
                    Letters.GblFunc_Add_FileToStore(System.IO.Path.GetTempPath & "CRMTemp" & "\" & objAttach.FileName, objAttach.FileName, DocStoreId)
                    ''Dim fso As New Scripting.FileSystemObject
                    'fso.DeleteFile(System.IO.Path.GetTempPath & "CRMTemp\" & objAttach.FileName, True)
                    'System.IO.File.Delete(System.IO.Path.GetTempPath & "CRMTemp\" & objAttach.FileName)
                End If
            Next
            'Directory.Delete(System.IO.Path.GetTempPath & "CRMTemp\")


            DeleteDirContents(New IO.DirectoryInfo(System.IO.Path.GetTempPath & "CRMTemp\"))
            oApp = Nothing
            oNS = Nothing
            oItems = Nothing
            oMsg = Nothing
            Return True
        Catch ex As Exception
            CommonFuncs.DisplayMessage("Error in Attaching the documents. Please contact IT", CommonDialog.CustomDialogIcons.Information, "Error")
            Return False
        End Try


    End Function
    ''' <summary>
    ''' Deletes the contents of a directory.
    ''' </summary>
    ''' <param name="dir">Directory to delete the contents of.</param>

    Public Sub DeleteDirContents(ByVal dir As IO.DirectoryInfo)
        Try

            Dim fa() As IO.FileInfo
            Dim f As IO.FileInfo

            fa = dir.GetFiles

            For Each f In fa
                f.Delete()
            Next

            Dim da() As IO.DirectoryInfo
            Dim d1 As IO.DirectoryInfo

            da = dir.GetDirectories
            For Each d1 In da
                DeleteDirContents(d1)
            Next
            dir.Delete()

        Catch ex As Exception

        End Try
    End Sub


    Private Sub grdInbox_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdInbox.SelectionChanged
        Try
            Dim currentRowIndex As Integer = grdInbox.SelectedIndex
            Dim currentRow As DataRowView = CType(grdInbox.Items(currentRowIndex), DataRowView)
            Me.Cursor = Cursors.Wait
            If Not currentRow Is Nothing Then
                txtMessage.Text = Me.GetMessageMAPI(currentRow(4).ToString())
            End If
            Me.Cursor = Cursors.Arrow

        Catch ex As Exception

        End Try
    End Sub
End Class
